<?php
namespace src\logic;
use \classlib\core as C;
class lupfile {
	/**
	 * 定义缩略图文件名前缀
	 * @var unknown
	 */
	const SM = '_sm';
	
	/**
	 * 删除S3上的图片资料信息
	 * @param unknown $path
	 */
	public static function delete($path) {
		@unlink(WEBROOT.$path);
		$config = C\config::load('aws3', false);
		$s3     = new \classlib\store\awss3($config['access_key'], $config['access_secret'], $config['s3server']);
		$s3->deleteObject($config['bucket'], $path);
	}
	
	/**
	 * 讲置顶的图生成缩略图
	 * @param string $imgsrc
	 * @param number $userid
	 * @param number $stype
	 * @param number $scope
	 * @return bool or string
	 */
	public static function thumbnail($imgsrc, $userid, $stype, $scope=2) {
		$upfile    = C\config::load('aws3', false);
		$imgfile   = $upfile['upbase'].$imgsrc;
		$size_info = getimagesize($imgfile);
		$lsize     = array('w'=>$size_info[0]/$scope, 'h'=>$size_info[1]/$scope);
		$filename  = basename($imgfile);
		$dirname   = dirname($imgfile);
		$dotnpos   = strrpos($filename, '.');
		$nimgfile  = '';
		if ($dotnpos > 0) {
			$nimgfile = $dirname.'/'.substr($filename, 0, $dotnpos).self::SM.substr($filename, $dotnpos);
		} else {
			$nimgfile = $imgfile.self::SM;
		}
		if ($lsize['w'] <= 200 || $lsize['h'] <= 200) {
			copy($imgfile, $nimgfile);
		} else {
			$subfix     = strtolower(substr($size_info['mime'], 6));
			$srcimg     = NULL;
			if (strcmp($subfix, 'jpg') == 0 || strcmp($subfix, 'jpeg') == 0) {
				$srcimg = imagecreatefromjpeg($imgfile);
			} else if(strcmp($subfix, 'png') == 0) {
				$srcimg = imagecreatefrompng($imgfile);
			} else if(strcmp($subfix, 'gif') == 0) {
				$srcimg = imagecreatefromgif($imgfile);
			} else  {
				return false;
			}
			$newimg     = imagecreatetruecolor($lsize['w'], $lsize['h']);
			imagealphablending($newimg, FALSE);
			imagesavealpha($newimg, TRUE);
			imagecopyresampled($newimg, $srcimg, 0, 0, 0, 0, $lsize['w'], $lsize['h'], $size_info[0], $size_info[1]);
			//保存图片
			if (strcmp($subfix, 'jpg') == 0 || strcmp($subfix, 'jpeg') == 0) {
				imagejpeg($newimg, $nimgfile);
			} else if(strcmp($subfix, 'png') == 0) {
				imagepng($newimg, $nimgfile);
			} else if(strcmp($subfix, 'gif') == 0) {
				imagegif($newimg, $nimgfile);
			}
			imagedestroy($newimg);
			imagedestroy($srcimg);
		}
		//将图片同步到远程 是否直接同步到亚马逊s3服务
		$s3path  = substr($nimgfile, strlen($upfile['upbase']));
		if (isset($upfile['sync_s3']) && $upfile['sync_s3']) {
			if (!self::syncaws($s3path, $nimgfile, $userid, $stype)) {
				return false;
			}
		}
		return $s3path;
	}
	
	/**
	 * 取文件扩展名  
	 * @param string $filename
	 * @param bool   $withdot
	 */
    public static function file_ext($filename) {
    	$result = pathinfo($filename, PATHINFO_EXTENSION);
        return $result;
    }
    
    /**
     * 执行附件上传
     * @param view_abstract $view
     * @param string  $stype avtar appbg activity 
     * @param string $fsname
     * @return string
     */
    public static function transfer($view, $stype, $fsname = 'Filedata') {
    	$path = '';
    	$lang = C\lang::inst('web');
    	if(isset($_FILES[$fsname]) && is_uploaded_file($_FILES[$fsname]['tmp_name'])) {
    		if ($_FILES[$fsname]['error'] != UPLOAD_ERR_OK) {
    			@unlink($_FILES[$fsname]['tmp_name']);
    			$view->assign_error($fsname, $lang->txt('core', '504'));
    		}
    		$path = self::dolocal($_FILES[$fsname], $subfix, $stype);
    		if (!$path) {
    			@unlink($_FILES[$fsname]['tmp_name']);
    			$view->assign_error($fsname, $lang->txt('core', '504'));
    		}
    	}
    	return $path;
    }
    
    /**
     * 给接口调用直接提交流数据
     * @param view_abstract $view
     * @param string $origin
     * @param string $subfix
     * @param int    $userid
     * @param string $stype
     * @return string
     */
    public static function dostream($view, $origin, $subfix, $userid, $stype) {
    	$lang     = C\lang::inst('web');
    	$upfile   = C\config::load('aws3', false);
    	$s3_path  = sprintf('%s%s/%s/%d', $upfile['upfile'], date('Ym'), $stype, $userid%500);
    	if (!is_dir($s3_path)) {
    		mkdir($s3_path, 0777, true) or $view->assign_error(505, $lang->txt('core', '505'));
    	}
    	$s3_path .= '/'.C\rand_str(8).'.'.$subfix;
    	file_put_contents($s3_path, $origin);
    	if (!getimagesize($s3_path)) {
    		unlink($s3_path);
    		$view->assign_error(701, $lang->txt('core', '701'));
    	}
    	//是否直接同步到亚马逊s3服务
    	$s3path = substr($s3_path, strlen($upfile['upbase']));
    	if (isset($upfile['sync_s3']) && $upfile['sync_s3']) {
    	 	if (!self::syncaws($s3path, $s3_path, $userid, $stype)) {
    			$view->assign_error(504, $lang->txt('core', '504'));
    		}
    	}
    	return $s3path;
    }
    
    /**
     * 传输同步到ryns
     * @param string $s3path
     * @param string $fspath
     * @param int    $userid
     * @param string $channal
     * @return bool
     */
    public static function syncaws($s3path, $fspath, $userid, $channal) {
    	//是否直接同步到亚马逊s3服务
    	$config = C\config::load('aws3', false);
    	$s3     = new \classlib\store\awss3($config['access_key'], $config['access_secret'], $config['s3server']);
    	if ($s3->uploadFile($config['bucket'], $s3path, $fspath)) {//记录到DB当中来
    		$data = array('userid'=>$userid, 'channel'=>$channal, 'url'=>$s3path,
    			'type'=>6, 'status'=>0, 'size'=>filesize($fspath), 'stime'=>C\config::$nowtime);
    		C\model::load('main.log.attachment')->new_one($data);
    		return true;
    	}
    	return false;
    }
      
	/**
	 * 上传文件 上传到本地目录
	 * @param string $filearr
	 * @param string $subfix
	 * @param string $stype
	 * @param string $userid
	 * @return string
	 */
	public static function dolocal(&$filearr, $subfix, $stype, $userid=0) {
		$upfile  = C\config::load('aws3', false);
		$s3_path = $upfile['upfile'].sprintf('%s/%s/', $stype, date('ymd'));
		if (!is_dir($s3_path)) {
			mkdir($s3_path, 0777, true);
		}
		$s3_path.= C\rand_str(8).'.'.$subfix;
		if (!move_uploaded_file($filearr['tmp_name'], $s3_path)) {
			@unlink($filearr['tmp_name']);
			return '';
		}
		//是否直接同步到亚马逊s3服务
		$s3path = substr($s3_path, strlen($upfile['upbase']));
		if (isset($upfile['sync_s3']) && $upfile['sync_s3']) {
			if (!self::syncaws($s3path, $s3_path, $userid, $stype)) {
    			return '';
    		}
		}
		return $s3path;
	}
	
	/**
	 * 抓取图片到本地目录
	 * @param string $filearr
	 * @param string $subfix
	 * @param string $stype
	 * @param string $userid
	 * @return string
	 */
	public static function dopic($file, $subfix, $stype, $userid=0) {
		$upfile  = C\config::load('aws3', false);
		$s3_path = $upfile['upfile'].sprintf('%s/%s/', $stype, date('ymd'));
		if (!is_dir($s3_path)) {
			mkdir($s3_path, 0777, true);
		}
		$s3_path.= C\rand_str(8).'.'.$subfix;
		$file    = file_get_contents($file);
		file_put_contents($s3_path, $file);
		//是否直接同步到亚马逊s3服务
		$s3path = substr($s3_path, strlen($upfile['upbase']));
		if (isset($upfile['sync_s3']) && $upfile['sync_s3']) {
			if (!self::syncaws($s3path, $s3_path, $userid, $stype)) {
    			return '';
    		}
		}
		return $s3path;
	}
}